package com.company.project.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/2/27.
 */
public class BeanMapUtil {
    //JavaBean转换为Map
    public static Map<String,Object> bean2map(Object bean,Class clazz){
        Map<String,Object> map = new HashMap<>();
        //获取指定类（Person）的BeanInfo 对象
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(clazz, Object.class);
            //获取所有的属性描述器
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor pd : pds) {
                String key = pd.getName();
                Method getter = pd.getReadMethod();
                Object value = null;
                value = getter.invoke(bean);
                map.put(key, value);
            }
        }catch (IllegalAccessException|InvocationTargetException|IntrospectionException e) {
            e.printStackTrace();
        }
        return map;
    }

    //Map转换为JavaBean
    public static <T> T map2bean(Map<String,Object> map,Class<T> clz) {
        try {
            //创建JavaBean对象
            T obj = clz.newInstance();
            //获取指定类的BeanInfo对象
            BeanInfo beanInfo = Introspector.getBeanInfo(clz, Object.class);
            //获取所有的属性描述器
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor pd : pds) {
                Object value = map.get(pd.getName());
                Method setter = pd.getWriteMethod();
                setter.invoke(obj, value);
            }
            return obj;
        }catch (IllegalAccessException|InvocationTargetException|IntrospectionException|InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }
}
